package com.imranstechnology.homeexpensemanager;

import java.util.Date;
import java.util.Locale;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.imranstechnology.homeexpensemanager.util.SystemUiHider;
import com.imranstechnology.homeexpensemanager.utils.DateUtil;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 * 
 * @see SystemUiHider
 */
public class ExpenseDashBoard extends Activity {
	/**
	 * Whether or not the system UI should be auto-hidden after
	 * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
	 */
	private static final boolean AUTO_HIDE = true;

	/**
	 * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
	 * user interaction before hiding the system UI.
	 */	
	private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

	/**
	 * If set, will toggle the system UI visibility upon interaction. Otherwise,
	 * will show the system UI visibility upon interaction.
	 */
	private static final boolean TOGGLE_ON_CLICK = true;

	/**
	 * The flags to pass to {@link SystemUiHider#getInstance}.
	 */
	private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;

	/**
	 * The instance of the {@link SystemUiHider} for this activity.
	 */
	private SystemUiHider mSystemUiHider;
	public static final String ADD_UNIT_ID = "ca-app-pub-3426427292261762/9322909938";
//	public static final String ADD_UNIT_ID = "a152a30fce7daab";
	private EditText mTotalExpense;
	private EditText mYearlyExpense;
	private EditText mMonthlyExpense;
	private EditText mDailyExpense;
	private Button mBtnCallAddExoense;
	private Editor editor;
	private AdView adView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		String lang = PreferenceManager.getDefaultSharedPreferences(this).getString(SettingsActivity.DEFAULT_LANGUAGE_KEY, "ar");
		String currency = PreferenceManager.getDefaultSharedPreferences(this).getString(SettingsActivity.DEFAULT_CURRENCY_KEY, "JOD");

		Resources res = getResources();
		DisplayMetrics dm = res.getDisplayMetrics();
		Configuration conf = res.getConfiguration();
		conf.locale = new Locale(lang);
		res.updateConfiguration(conf, dm);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_expense_dash_board);
		if(!ExpenseMemStore.isInitalized){
			SharedPreferences preferences = getSharedPreferences(HomeExpenseConstants.APP_PREPFERENCE_AREA, MODE_PRIVATE);
			//	editor = preferences.edit();
			//fill5YearsData(preferences.edit());
			ExpenseMemStore.initExpenseEntityFromPrefs(preferences);
		}
		final View contentView = findViewById(R.id.homeExpenseFrame);

		final View controlsView = contentView; //findViewById(R.id.tableLayout);
		mBtnCallAddExoense = (Button)findViewById(R.id.btnCallAddExpense);
		mTotalExpense = (EditText)findViewById(R.id.txtTotalExpense);
		mYearlyExpense = (EditText)findViewById(R.id.txtYearlyExpense);
		mMonthlyExpense = (EditText)findViewById(R.id.txtMonthlyExpense);
		mDailyExpense = (EditText)findViewById(R.id.txtDailyExpense);

		TextView curr = null;
		curr = (TextView)findViewById(R.id.totalExpenseCurr);
		curr.setText(currency);
		curr = (TextView)findViewById(R.id.yearExpenseCurr);
		curr.setText(currency);
		curr = (TextView)findViewById(R.id.monthlyExpenseCurr);
		curr.setText(currency);
		curr = (TextView)findViewById(R.id.todaysExpenseCurr);
		curr.setText(currency);
		mBtnCallAddExoense.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				callAddExpense(v);
			}

			
		});
		
		// Upon interacting with UI controls, delay any scheduled hide()
		// operations to prevent the jarring behavior of controls going away
		// while interacting with the UI.
		mBtnCallAddExoense.setOnTouchListener(
				mDelayHideTouchListener);
		LinearLayout adRow = (LinearLayout)findViewById(R.id.AddTableRow);
		adView = new AdView(this);
		adView.setAdUnitId(ADD_UNIT_ID);
		AdSize adSize = new AdSize(300, 50);
		adView.setAdSize(AdSize.BANNER);
		adRow.addView(adView);
		AdRequest adReq = new AdRequest.Builder().build();
		adView.loadAd(adReq);
	}
	private void fill5YearsData(Editor editor){
		int days = 365*3;
		String[] cat = getResources().getStringArray(R.array.expense_category);
		Date curDate = DateUtil.stringToDate("27/10/2008");
		for(int i = 1;i<= days;i++){
			for(int j=0;j<cat.length;j++){
				ExpenseMemStore.addExpense(3f, curDate, j);
			}
			curDate = new Date(curDate.getTime() + (24*60*60*1000));
		}
		ExpenseMemStore.storeMemExpense(editor);

	}
	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);

		// Trigger the initial hide() shortly after the activity has been
		// created, to briefly hint to the user that UI controls
		// are available.
		delayedHide(300);
	}
	private void bindDataToUI(){
		mTotalExpense.setText(""+ExpenseMemStore.EXPENSEE_ENTITY.getTotalExpense());
		mYearlyExpense.setText(""+ExpenseMemStore.EXPENSEE_ENTITY.getYearlyExpense());
		mMonthlyExpense.setText(""+ExpenseMemStore.EXPENSEE_ENTITY.getMonthlyExpense());
		mDailyExpense.setText(""+ExpenseMemStore.EXPENSEE_ENTITY.getDailyExpense());
	}
	/**
	 * Touch listener to use for in-layout UI controls to delay hiding the
	 * system UI. This is to prevent the jarring behavior of controls going away
	 * while interacting with activity UI.
	 */
	View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
		@Override
		public boolean onTouch(View view, MotionEvent motionEvent) {
			if (AUTO_HIDE) {
				delayedHide(AUTO_HIDE_DELAY_MILLIS);
			}
			return false;
		}
	};

//	Handler mHideHandler = new Handler();
//	Runnable mHideRunnable = new Runnable() {
//		@Override
//		public void run() {
//			mSystemUiHider.hide();
//		}
//	};

	/**
	 * Schedules a call to hide() in [delay] milliseconds, canceling any
	 * previously scheduled calls.
	 */
	private void delayedHide(int delayMillis) {
//		mHideHandler.removeCallbacks(mHideRunnable);
//		mHideHandler.postDelayed(mHideRunnable, delayMillis);
	}
	private void callAddExpense(View v) {
		startActivity(new Intent(this, AddExpense.class));
	}
	@Override
	protected void onResume() {
		super.onResume();
		ExpenseMemStore.fixDailyAmounts();
		bindDataToUI();
        adView.resume();
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.options_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			//NavUtils.navigateUpFromSameTask(this);
			return false;
		case R.id.action_settings:
			startActivity(new Intent(this, SettingsActivity.class));
			return true;
		case R.id.expense_detail_view:
			startActivity(new Intent(this, ExpenseDetailView.class));
			return true;
		case R.id.monthly_expense_list_view:
			startActivity(new Intent(this, MonthlyExpenseView.class));
			return true;
		}	
		return super.onOptionsItemSelected(item);
	}
	 @Override
	    protected void onPause() {
	        adView.pause();
	        super.onPause();
	    }


	    @Override
	    protected void onDestroy() {
	        adView.destroy();
	        super.onDestroy();
	    }
}
